<?php

/**
 * This is the model class for table "zy_agent_recharge".
 *
 * The followings are the available columns in table 'zy_agent_recharge':
 * @property integer $agent_recharge_id
 * @property string $recharge_time
 * @property integer $recharge_number
 * @property integer $recharge_type
 * @property integer $user_id
 * @property integer $agent_id
 * @property integer $company_number
 * @property string $txnid
 * @property integer $package_id
 * @property integer $is_delete
 * @property string $crate_time
 * @property string $crate_user
 * @property string $update_time
 * @property string $update_user
 */
class AgentRecharge extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return AgentRecharge the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'zy_agent_recharge';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('recharge_type, user_id, agent_id, company_number, package_id, is_delete', 'numerical', 'integerOnly'=>true),
			array('recharge_number', 'numerical', 'integerOnly'=>false),
			array('txnid, crate_user, update_user', 'length', 'max'=>50),
			array('recharge_time, crate_time, update_time', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('agent_recharge_id, recharge_time, recharge_number, recharge_type, user_id, agent_id, company_number, txnid, package_id, is_delete, crate_time, crate_user, update_time, update_user', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			//'agent_recharge_id' => 'Agent Recharge',
            'recharge_time' =>Yii::t('base','Recharge Time'),
			'recharge_number' =>Yii::t('base','Recharge Number'),
			'recharge_type' =>Yii::t('base','Recharge Type'),
			'user_id' => Yii::t('base','User Name'),
			'agent_id' => Yii::t('base','Agent Name'),
			'company_number' => 'Company Number',
			'txnid' => Yii::t('base', 'Txnid'),
			'package_id' =>Yii::t('base', 'Package'),
			'is_delete' => 'Is Delete',
			'crate_time' => 'Crate Time',
			'crate_user' => 'Crate User',
			'update_time' => 'Update Time',
			'update_user' => 'Update User',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('agent_recharge_id',$this->agent_recharge_id);
		$criteria->compare('recharge_time',$this->recharge_time,true);
		$criteria->compare('recharge_number',$this->recharge_number);
		$criteria->compare('recharge_type',$this->recharge_type);
                if(yii::app()->user->level() != 1){
		$criteria->compare('user_id',yii::app()->user->id);
                }else{
                    $criteria->compare('user_id',$this->user_id);
                }
		$criteria->compare('agent_id',$this->agent_id);
		$criteria->compare('company_number',$this->company_number);
		$criteria->compare('txnid',$this->txnid,true);
		$criteria->compare('package_id',$this->package_id);
		$criteria->compare('is_delete',$this->is_delete);
		$criteria->compare('crate_time',$this->crate_time,true);
		$criteria->compare('crate_user',$this->crate_user,true);
		$criteria->compare('update_time',$this->update_time,true);
		$criteria->compare('update_user',$this->update_user,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
        
        
        
//pay with the credit card; 信用卡
public function cc_capture($params) {
    
$string = <<<XML
<SecurePayMessage />
XML;

          $xml = new SimpleXMLElement($string);

	$timestamp = strftime("%Y%d%m%H%M%S000000%z");
        
	$amount = number_format($params['amount']*100,0,'','');

	$messageInfo = $xml->addChild('MessageInfo');

	$messageInfo->addChild('messageID', md5("NovaTel_" . $params['invoiceref']));

	$messageInfo->addChild('messageTimestamp', $timestamp);

	$messageInfo->addChild('timeoutValue', 60);

	$messageInfo->addChild('apiVersion', 'xml-4.2');

	$merchantInfo = $xml->addChild('MerchantInfo');

	$merchantInfo->addChild('merchantID', 'WEJ0024');

	$merchantInfo->addChild('password', 'm9JD6TQT');
	$xml->addChild('RequestType', 'Payment');

	$payment = $xml->addChild('Payment');

	$txnList = $payment->addChild('TxnList');

	$txnList->addAttribute('count', 1);


	$txn = $txnList->addChild('Txn');

	$txn->addAttribute('ID', 1);

	$txn->addChild('txnType', 0);

	$txn->addChild('txnSource', 23);

	$txn->addChild('amount', $amount);

	$txn->addChild('currency', "AUD");

	$txn->addChild('purchaseOrderNo', "test:"  . $params['invoiceref']);


	$cardInfo = $txn->addChild('CreditCardInfo');

	$cardInfo->addChild('cardNumber', $params['cardnum']);

	$cardInfo->addChild('expiryDate', $params['cardexp']);

	$gatewayData = $xml->asXML();

	$ch = curl_init("https://api.securepay.com.au/xmlapi/payment");
	curl_setopt($ch, CURLOPT_POST, 1);

	curl_setopt($ch, CURLOPT_POSTFIELDS, $gatewayData);

	curl_setopt($ch, CURLOPT_TIMEOUT, 60);

	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

	@curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        
	$result = curl_exec($ch);


	$log = array("status"=>"", "message"=>"", "txnid"=>"");

	if(curl_errno($ch)) {

		$log['status'] = "fail";

		$log['message'] = "Connection Error";

		return $log;

	}

	else {



		$result_xml = new SimpleXMLElement($result);

		$txn_response = $result_xml->xpath('//Txn[@ID=1]');

		$txn_response = $txn_response[0];



		

		if (strtolower($txn_response->approved) == "yes") {

			$log['status'] = "success";

			$log['message'] = "Amount: " . $params['amount'];

			$log['txnid'] = strtolower($txn_response->txnID);

			return $log;

		} elseif (strtolower($txn_response->approved) == "no") {

			$log['status'] = "fail";

			$log['message'] = "NOT Approved by SecurePayAU";

        	return $log;

    	} else {

			$log['status'] = "fail";

			$log['message'] = "Error Occured";

			return $log;

		}
	}
}
        
        
        
 //pay with the direct entry; 转账
public function cc_bankpay($params){
	$timestamp = strftime("%Y%d%m%H%M%S000000%z");
	$amount = number_format($params['amount']*100,0,'','');

$xml = new SimpleXMLElement('<SecurePayMessage />');

$messageInfo = $xml->addChild('MessageInfo');
$messageInfo->addChild('messageID', md5("NovaTel_" . $params['invoiceref']));
$messageInfo->addChild('messageTimestamp', $timestamp);
$messageInfo->addChild('timeoutValue', 60);
$messageInfo->addChild('apiVersion', 'xml-4.2');

$merchantInfo = $xml->addChild('MerchantInfo');
$merchantInfo->addChild('merchantID', 'NTN00');
$merchantInfo->addChild('password', '27r2fjjy');

$xml->addChild('RequestType', 'Payment');
$payment = $xml->addChild('Payment');
$txnList = $payment->addChild('TxnList');
	$txnList->addAttribute('count', 1);

	$txn = $txnList->addChild('Txn');
	$txn->addAttribute('ID', 1);
	$txn->addChild('txnType', 15);
	$txn->addChild('txnSource', 23);
	$txn->addChild('amount', $amount);
	$txn->addChild('currency', "AUD");
	$txn->addChild('purchaseOrderNo', "ref:"  . $params['invoiceref']);

	$directInfo = $txn->addChild('DirectEntryInfo');
	$directInfo->addChild('bsbNumber',$params['cc_bsbnumber']);
	$directInfo->addChild('accountNumber', $params['cc_accountnumber']);
	$directInfo->addChild('accountName', $params['cc_accountname']);

	$gatewayData = $xml->asXML();
	
	$ch = curl_init("https://api.securepay.com.au/xmlapi/directentry");

	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $gatewayData);
	curl_setopt($ch, CURLOPT_TIMEOUT, 60);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	@curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);


	$result = curl_exec($ch);
	echo $result;
	$log = array("status"=>"", "message"=>"", "txnid"=>"");
	
	if(curl_errno($ch)) {
		$log['status'] = "fail";
		$log['message'] = "Connection Error";
		return $log;
	}
	else {

		$result_xml = new SimpleXMLElement($result);
		$txn_response = $result_xml->xpath('//Txn[@ID=1]');
		$txn_response = $txn_response[0];
		
		
		if (strtolower($txn_response->approved) == "yes") {
			$log['status'] = "success";
			$log['message'] = "Amount: " . $params['amount'];
			$log['txnid'] = strtolower($txn_response->txnID);
			return $log;
		} elseif (strtolower($txn_response->approved) == "no") {
			$log['status'] = "fail";
			$log['message'] = "NOT Approved by SecurePayAU";
        	return $log;
    	} else {
			$log['status'] = "fail";
			$log['message'] = "Error Occured";
			return $log;
		}
		
	}
}



public function send_email_to_admin ($subject, $message)
{

	$to = "billing@webnova.com.au";

	$header = "From: billing@webnova.com.au" . "\r\n" .

		"Reply-To: billing@webnova.com.au" . "\r\n";

//$to = "zy.shulei@gmail.com";
//$header = "From:billing@webnova.com.au" . "\r\n" ."Reply-To: zy.shulei@gmail.comf" . "\r\n";
	@mail($to, $subject, $message, $header);

	

	return;

}
/**
 * 获取默认付款方式
 */
public function  getDefaultpay($user_id){
    $sql="select * from zy_card_info where user_id=".$user_id;
    $result = yii::app()->db->createCommand($sql)->queryAll();
    return $result[0]['defaultpay'];
}
/**
 * 获取代理人公司编号
 * @return type
 */
public function getCompanyNumber($user_id){
    $sql="select * from zy_agent_company where user_id=".$user_id;
    $result = yii::app()->db->createCommand($sql)->queryAll();
    return $result[0]['agent_number'];
}
/**
 * 充值完成后，向代理人的信誉度里增加充值的金额！
 * @return boolean
 */
public function rechangeSuccess() {
        $recharge_type = $_POST['AgentRecharge']['recharge_type'];
        $recharge_number = $_POST['AgentRecharge']['recharge_number'];
        $agent_id = $_POST['AgentRecharge']['agent_id'];
        $package_id =  $_POST['AgentRecharge']['package_id'];
        if (yii::app()->user->level3() == 5) {  //个人代理
            $agentperson = AgentPerson::model()->find('agent_person_id='.$agent_id);
            $agentperson->credit = $agentperson->credit + $recharge_number;
            $agentperson->update();
        } else if($recharge_type == 3){ //押金付款
        	$userservice=UserService::model()->find('user_id='.yii::app()->user->id.' and service_id =12');
			//$cost= $_POST['AgentRecharge']['recharge_number'];
			$userservice->deposit=$userservice->deposit - $recharge_number;
		if($userservice->deposit<0){
			 $this->addError("cost","The cost is more than deposit");
			return false;
		}
                $userservice->update();
        }elseif(yii::app()->user->level3() == 8 && $recharge_type != 3){    //修改3G用户组
        	 $result = Custom::model()->getEquipmentSimCardByUserId(yii::app()->user->id);
             $i = rechargeUpdateUserGroup($result,$package_id);
             if($i > 0){
                 return true;
             }else{
                 return false;
             }
        }else{ //代理商增加额度
            $agentcompany = AgentCompany::model()->find('agent_id='.$agent_id);
            $agentcompany->credit = $agentcompany->credit + $recharge_number;
            $agentcompany->update();
        }
        return true;
    }
/**
 * 充值类型
 * @param type $id
 * @return type
 */
public function getRechargeType($id){
		if($id==1){
			return Yii::t('base','Card Infos');
		}elseif($id==2){
			return Yii::t('base','Bank Card');
		}elseif($id==4){
			return Yii::t('base','remittance');
                }elseif($id==3){
                        return Yii::t('base','Deduct the deposit');
                }
	}
/**
 * 获取套餐名称
 * @param type $package_id
 * @return type
 */
public function getPackageName($package_id){
    $package = Package::model()->find('package_id='.$package_id);
    return $package->package_name;
}
}